package com.example.server;

import java.util.List;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import com.example.silvercare.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class GetMyLocation extends Activity {

	String latitude;
	String longitude;
	String address;
	String fingerprint;
	EditText Latitude;
	EditText Longitude;
	EditText Address;
	EditText Fingerprint;
	
	LocationManager mLocationManager;
	Location mLocation;
	LocationListener listener;
	List<String> providers;
	
	//simulation
	Timer timer = new Timer();
	double simulateLatitude;
	double simulateLongitude;
	double simulateFingerprintX;
	double simulateFingerprintY;
	double simulateFingerprintZ;
	
	final Handler UpdateHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {      
		             case 1:
		            	setAddress();
		                  break;     
		             case 2:
		         		setCoordinates();
		        		setFingerprint();
		        		setAddress();
		        		break;
		              }      
		              super.handleMessage(msg);  
		         }    
		     }; 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.location);
		latitude = "null";
		longitude = "null";
		fingerprint = "null";
		address = "null";
        Latitude = (EditText) findViewById(R.id.Lat);
        Longitude = (EditText) findViewById(R.id.Lon);
        Address = (EditText) findViewById(R.id.Addr);
        Fingerprint = (EditText) findViewById(R.id.Fingerprint);
        Button mapviewButton = (Button) findViewById(R.id.mapviewButton);
        
        //simulation
        simulateLatitude = 0;
        simulateLongitude = 0;
        simulateFingerprintX = 0;
        simulateFingerprintY = 0;
        simulateFingerprintZ = 0;
        
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        providers = mLocationManager.getProviders(true); 
        listener = new LocationListener() {  
			public void onLocationChanged(Location location) {
				mLocation = location;
				if(mLocation != null)
				{
					latitude = ""+mLocation.getLatitude();
					longitude = ""+mLocation.getLongitude();
					setCoordinates();
					QueryMapEngine();
				}				
			}  
			public void onProviderDisabled(String provider){}  
			public void onProviderEnabled(String provider){}  
			public void onStatusChanged(String provider, int status,Bundle extras){}  
		};
		
		
        //getMyCurrentLocation();
		simulateMyCurrentLocation();
		setCoordinates();
		setFingerprint();
		//QueryMapEngine();
		setAddress();
        
        mapviewButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.example.server.MapViewActivity"));
			}
        	
        });
	}
	
	//Query Map Engine and Get Address
	private void getMyCurrentLocation(){
		 
		for (String provider : providers) {  
			mLocationManager.requestLocationUpdates(provider, 1000, 1, listener);
	 
			mLocation = mLocationManager.getLastKnownLocation(provider);
			if(mLocation != null)
			{
				latitude = ""+mLocation.getLatitude();
				longitude = ""+mLocation.getLongitude();
			}
		}
	}
	
	private void simulateMyCurrentLocation(){
		/*
		final Handler handler = new Handler(){
			public void handleMessage(Message msg) {
				switch (msg.what) {      
			             case 1:
			            	simulateLatitude = ((double)((int)(simulateLatitude*10)+1)%10)/10;
			            	simulateLongitude = ((double)((int)(simulateLongitude*10)+1)%10)/10;
			            	latitude = ""+simulateLatitude;
			 				longitude = ""+simulateLongitude;
			 				fingerprint = ""+simulateFingerprintX+", "+simulateFingerprintY+", "+simulateFingerprintZ;
							setCoordinates();
							setFingerprint();
							
							mLocationManager.removeUpdates(listener);
							QueryMapEngine();
							for (String provider : providers) {  
								mLocationManager.requestLocationUpdates(provider, 1000, 1, listener);
							}
							
			                  break;      
			              }      
			              super.handleMessage(msg);  
			         }    
			     };  


		timer.scheduleAtFixedRate(new TimerTask() {

			public void run() {
				 Message message = new Message();      
				 message.what = 1;      
				 handler.sendMessage(message);    
			}
		}, 0000, 5000);		*/		
		
		timer.scheduleAtFixedRate(new TimerTask() {

			public void run() {
				latitude = LocationUpdateService.latitude;
				longitude = LocationUpdateService.longitude;
				fingerprint = LocationUpdateService.fingerprint;
				address = LocationUpdateService.address;
				
				 Message message = new Message();      
				 message.what = 2;      
				 UpdateHandler.sendMessage(message);    
			}
		}, 0000, 5000);
	}
	
	private void setCoordinates(){
        Latitude.setText(latitude);
        Longitude.setText(longitude);       
	}
	private void setFingerprint(){
		Fingerprint.setText(fingerprint);
	}
	private void setAddress(){
		Address.setText(address);
	}
	
	private void QueryMapEngine(){
		Thread initBkgThread = new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				//sent latitude and longitude to map engine

				MapEngineClient c=new MapEngineClient();
				try{
						address = c.processService(1,"10.3|2.5|none|none|none");
						if(address == null)
							System.out.println("Map Engine Return Null");
						else
							System.out.println("Map Engine Return "+address);
						
				}catch(Exception e)
				{
					e.printStackTrace();
				}finally{
					if(c.connection==1)
						c.close();
				}
				//setAddress();
				if(address == null)
					System.out.println("Map Engine Return Null");
				else
					System.out.println("Map Engine Return "+address);
				Message message = new Message();      
			    message.what = 1;      
			    UpdateHandler.sendMessage(message); 
				


			}
			
		});
		initBkgThread.start();

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		timer.cancel();
		mLocationManager.removeUpdates(listener);
		super.onDestroy();
	}

}
